package com.lyw.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyw.gulimall.product.entity.SpuInfoEntity;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyw.common.utils.PageUtils;
import com.lyw.common.utils.Query;

import com.lyw.gulimall.product.dao.SkuInfoDao;
import com.lyw.gulimall.product.entity.SkuInfoEntity;
import com.lyw.gulimall.product.service.SkuInfoService;
import org.springframework.util.StringUtils;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.save(skuInfoEntity);
    }

    @Override
    public IPage<Map<String, Object>> queryPageByCondition(Integer page, Integer limit, String sidx, String order, String key, Long catelogId, Long brandId, Integer min, Integer max) {
        Page<Map<String, Object>> result = new Page<>(page, limit);
        QueryWrapper<SpuInfoEntity> lqw = new QueryWrapper<SpuInfoEntity>();

        if (!StringUtils.isEmpty(key)) {
            lqw.and(wrapper -> {
                wrapper.eq("sku_id", key).or().like("sku_name", key);
            });
        }

        if (brandId != 0) {
            lqw.eq("brand_id", brandId);
        }

        if (catelogId > 0) {
            lqw.eq("catalog_id", catelogId);
        }

        if (!StringUtils.isEmpty(order)) {
            if (order.equalsIgnoreCase("asc")) {
                if (!StringUtils.isEmpty(sidx)) {
                    lqw.orderByAsc(sidx);
                } else {
                    lqw.orderByAsc("sku_id");
                }
            } else {
                if (!StringUtils.isEmpty(sidx)) {
                    lqw.orderByDesc(sidx);
                } else {
                    lqw.orderByDesc("sku_id");
                }
            }
        }

        if (min >= 0 && max > min) {
            lqw.ge("price", min);
            lqw.le("price", max);
        }

        IPage<Map<String, Object>> list = baseMapper.selectPageList(result, lqw);
        return list;
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {

        return this.list(new LambdaQueryWrapper<SkuInfoEntity>().eq(SkuInfoEntity::getSpuId, spuId));
    }
}